var currentNavClass = "main_nav_1";
var chatActivated = new Boolean(0);
var slideShowAnimation;
var continueSlideShowAnimation = true;

require([ "dojo", "dojo/_base/xhr", "dojo/on", "dojo/dom", "dojo/dom-class", "dojo/parser",
		"dojo/query", "dojo/dom-attr", "dojo/dom-style", "dojo/dom-construct", "dojo/keys",
		"dojox/widget/Standby", "dojo/fx/Toggler", "dojo/fx", "dojo/_base/fx", "dojox/fx/text", 
		"dojox/html", "dojox/validate", "dojo/_base/connect", 
		"dijit/registry", "dojo/_base/array", "dojo/_base/lang", "dojo/_base/declare",  
		"dojoCustom/profileWidget", "dojoCustom/paginationWidget", "dojo/io/iframe",
		"dojoCustom/slideShowWidget", "dojo/hash", "dojo/topic", "dojo/text!/static/json/usstates.json",
		"dojox/fx", 
		"dojox/html/_base", 
		"dijit/TooltipDialog", "dojo/NodeList-traverse", "dojo/NodeList-manipulate",
		"dojo/io/script",
		"dojox/validate/us", "dojox/validate/web", "dijit/form/CheckBox", "dijit/form/Textarea",
		"dijit/form/Select", "dijit/form/TextBox", "dijit/form/ValidationTextBox",
		"dijit/form/Button",
		"dijit/form/RadioButton", "dijit/form/Form", "dijit/form/ComboBox", "dojo/store/Memory",
		"dojo/domReady!" ],
		function(dojo, xhr, on, dom, domClass, parser, query, domAttr, domStyle, construct, keys,
				Standby, Toggler, fx, baseFx, text, html, validate, connect, registry, array, lang, declare,
				profileWidget, pagination, iframe, slideShow, hash, topic, states) {
			var standby = new Standby({
				target : "contentpane"
			});
			document.body.appendChild(standby.domNode);
			parser.parse();	
			
			clickmenu = function(target) {			
				loadContentPane(target);
				var highlightClass = domAttr.get(target, "nav-class");
				switchNavHighlight(highlightClass);
				paramUrl = domAttr.get(target, "content-url");
				if (paramUrl && paramUrl.indexOf("showQuestionnaire") != -1) {
					console.log("show questionnaire page"); 
					contenturl = "/profile/questionnaire.htm?userSetting=";
					loadContentPanewithUrl(contenturl); 
				}
			}
			
			topic.subscribe("/dojo/hashchange", function(changedHash){
			    var newLinkItem = query("." + changedHash + " > a");
			    if(newLinkItem.length > 0) {
			    	console.log(newLinkItem[0]);
			    	clickmenu(newLinkItem[0]);
			    }
			    if(changedHash.indexOf("sendmessage") != -1){
			    	handleExtProfileview("/profile/sendMessageForm.htm?toUser=" + changedHash.split("/")[1]); 
			    } else if(changedHash.indexOf("viewprofile") != -1){
			    	handleExtProfileview('/profile/extUserProfile.htm?userName='+ changedHash.split("/")[1]);
			    }
			  });
			
			switchNavHighlight = function(nav_class){
				query(".nav_li").forEach(function(node){
					domClass.remove(node, "active");
        		  }); 
				domClass.add(query("."+nav_class)[0], "active");  
			}
			
			updateContentPane = function(newContent){
				html.set(dojo.byId("contentpane"), newContent, {
			        executeScripts: true,
			        scriptHasHooks: false,
			        renderStyles: true
			    });
			}

			loadContentPaneCallback = function(newContent, ioargs) {
				console.log(ioargs);
				if(slideShowAnimation) {
					console.log("stopping animation"); 
					continueSlideShowAnimation = null;
					slideShowAnimation.stop();
				}
				var xhrstatus = ioargs.xhr.status;
				if (contenturl.indexOf("userChat.htm") != -1) {
					updateContentPane(newContent);
					parser.parse("chatting_pane");
					initializeChat();
					handleChatSubmit();
					
					standby.hide();
				} else if (contenturl.indexOf("showUsers.htm") != -1) {
					updateContentPane(newContent);
					if (newContent.indexOf("loginPageResponse") != -1) {
						parser.parse("login_content_td");
						handleLoginSubmit();
						loadUserRegistrationpage();
					} else {
						parser.parse("users_container");
						query(".user_chat").on("click", function(e) {
							startChatWindow(e.currentTarget);
							// loadContentPane(e.currentTarget); TODO vinod.neelam | user not taken to a new page.
						});
					}
					
					standby.hide();
				} else if(contenturl.indexOf("login.htm") != -1 || newContent.indexOf("slideShowContainer") != -1) { 
					destroyWidgets();
					updateContentPane(newContent);
					var t1 = "<span style='color: white;'><span>Speaker Nexus gives the opportunity to learn</span><br> <span>from Real people anywhere anytime.. </span> <br>- User One</span>";
					var t2 = "<span>I can listen or learn anything </span><br> <span> that I want from anyone I want..<br>- User Two</span>";
					new slideShow({urls : ['/static/images/nexus_home_slide1.png', '/static/images/nexus_home_slide2.png'], textArray : [t1, t2]}).placeAt("slideShowContainer"); 
					parser.parse("contentpane"); 
					handleLoginSubmit();
					loadUserRegistrationpage();		
					handleForgotPasswordLoad();
				} else if(contenturl.indexOf("updateQuestions.htm") != -1){
					destroyWidgets();
					updateContentPane(newContent);
					parser.parse("contentpane"); 
					handleAddQRow();
					handleAddQOption();
					handleUpdateQSubmit();	
					
					standby.hide();
				} else if(contenturl.indexOf("questionnaire.htm") != -1){
					onSubjDelete = function(e){
						var currentSubj = query(e).parent()[0];
						var subjValue = domAttr.get(currentSubj, "subjval");
						var subjInputValue = dojo.byId("subjectValuesInput").value.split(","); 
						var arraySubjId = array.indexOf(subjInputValue, subjValue);
						subjInputValue.splice(arraySubjId, 1);
						dojo.byId("subjectValuesInput").value = subjInputValue;
						console.log(subjValue);
						construct.destroy(currentSubj);
					}
					addSubjectValues = function(val){
						if(!val){
							val = dojo.byId("fieldInput").value;
						}
						if(val.length > 0){
							var newSubj = construct.create("li", {class: "bit-box", innerHTML : val, subjval: val });
							var subjInput = dojo.byId("subjectValuesInput");
							var arraySubjId = array.indexOf(subjInput.value.split(","), val); 
							if(arraySubjId == -1){
								if(subjInput.value.length != 0){
									subjInput.value = subjInput.value + "," + val;
								} else {
									subjInput.value = val;
								}
								
								var closeIcon = construct.create("a", {class: "closebutton", innerHTML : 'x', href: "javascript:void(0)", onclick: "onSubjDelete(this);"});  
								construct.place(newSubj, "subjectValues");
								construct.place(closeIcon, newSubj);
							}							
						}
						dojo.byId("fieldInput").value = "";
						dojo.byId("fieldInput").focus();
					}
					
					stateStore = new dojo.store.Memory({
				        data: [
				            {name:"Chemistry"},
				            {name:"Computer Science"},
				            {name:"English Language"},
				            {name:"French"},
				            {name:"History"},
				            {name:"Journalism"},
				            {name:"Life Science"},
				            {name:"Mathematics"},
				            {name:"Physical Science"},
				            {name:"Speech"},
				            {name:"Speech Communications"},
				            {name:"Technology Applications"}
				        ]
				    });
					usStatesStore = new dojo.store.Memory({
				        data: JSON.parse(states)
				    });
					
					destroyWidgets();
					updateContentPane(newContent);
					console.log("questionnaire form display"); 
					parser.parse("contentpane"); 
					var subjInput = null;
					if(dojo.byId("subjectValuesInput")){
						subjInput = dojo.byId("subjectValuesInput").value;
					}
					if(subjInput){
						array.forEach(subjInput.split(","), function(subjVal, index){
							var newSubj = construct.create("li", {class: "bit-box", innerHTML : subjVal });
							var closeIcon = construct.create("a", {class: "closebutton", innerHTML : 'x', href: "javascript:void(0)", onclick: "onSubjDelete(this);" }); 
							construct.place(newSubj, "subjectValues");
							construct.place(closeIcon, newSubj);
				        }); 
					}
					handleQuestionnaireFormSubmit();
					
					standby.hide();
				} else if(contenturl.indexOf("welcomePane.htm") != -1){
					destroyWidgets();
					updateContentPane(newContent);
					hookDashboardNav();
					query("#signup_home").on("click", function(e) {
						loadContentPane(e.currentTarget);
					});
					
					parser.parse("contentpane");
					
					standby.hide();
				} else if(contenturl.indexOf("searchHomePane.htm") != -1){
					destroyWidgets();
					updateContentPane(newContent);
					if(contenturl.indexOf("loggedIn") != -1){
						parser.parse("contentpane"); 
						handleProfileSearch();
						contenturl = "/profile/searchUserProfile.htm";
						loadContentPanewithUrlMaintainWidget(contenturl); 
					} else {
						parser.parse("login_content_td"); 
						handleLoginSubmit();
						loadUserRegistrationpage();		
						
						standby.hide();
					}					
				} else if(contenturl.indexOf("searchUserProfile.htm") != -1){
					var profContainer = construct.toDom("<div id='profileContainer'></div>");
					html.set(dojo.byId("profileContentPane"), profContainer);
					jsonContent = JSON.parse(newContent);
					var paginationItems = [];
					 array.forEach(jsonContent, function(profile, index){
				           // var newProfWidget = new profileWidget(profile).placeAt(profContainer);
				            paginationItems[index] = new profileWidget(profile); 
				        });
					 if(paginationItems.length > 0){
						 new pagination({items : paginationItems}).placeAt(profContainer);
					 }					 
					 parser.parse("profileContainer");
					standby.hide();
				} else if(contenturl.indexOf("reasonForRegistration.htm") != -1){
					destroyWidgets();
					updateContentPane(newContent);
					parser.parse("contentpane");
					
					standby.hide();
					handleReasonRegistrationFormSubmit();
				} else if(contenturl.indexOf("regReasonFormSubmit.htm") != -1){ 
					destroyWidgets();
					if(newContent.indexOf("show_questionnaire") != -1){
						contenturl = "/profile/questionnaire.htm?userSetting=";
						loadContentPanewithUrl(contenturl); 
					} else {
						window.location = "/";
					}
					
					standby.hide();
				} else if(contenturl.indexOf("accountInfo.htm") != -1){ 
					destroyWidgets();
					updateContentPane(newContent);
					
					standby.hide();
					parser.parse("contentpane");
					query("#edit_activities").on("click", function(e) {
						showReasonForRegistrationPage();
					});
				}  else if(contenturl.indexOf("extUserProfile.htm") != -1){
					updateContentPane(newContent);
					parser.parse("contentpane");
					standby.hide();
					query("#userProfile_sendMessage_link").on("click", function(e) {
						var userKey = domAttr.get(e.currentTarget, "email-attr");
						hash("sendmessage/" + userKey);
					});
				}  else if(contenturl.indexOf("forgotPassword.htm") != -1){ 
					destroyWidgets();
					updateContentPane(newContent);
					parser.parse("contentpane");
					handleForgotPasswordSubmit();
					
					standby.hide();
				} else if(contenturl.indexOf("forgotPasswordSubmit.htm") != -1){
					query("#forgotPasswordMessage > td")[0].innerHTML = newContent;
					dojox.fx.wipeTo({
					    node: "forgotPasswordMessage",
					    duration: 300,
					    height: 20
					  }).play();
					
					standby.hide();
				} else if(contenturl.indexOf("messages.htm") != -1){ 
					updateContentPane(newContent);
					parser.parse("contentpane");
					standby.hide();
				} else if(contenturl.indexOf("sendMessageForm.htm") != -1){
					updateContentPane(newContent);
					var userDataList;
					var userListReq = {
							url : "/profile/getAllUsers.htm", 
							load : function(data){
								//userDataList = '[{"firstName":"Speaker","lastName":"Nexus","email":"sample2"}]';
								userDataStore = new dojo.store.Memory({
							        data:  JSON.parse(data)
							    });
								parser.parse("contentpane");
								handleSendMessageSubmit();
								standby.hide();
							},
							error : function() {
								console.log(" error while pulling all users"); 
								standby.hide();
							}
						};
					//xhr.get(userListReq);
					parser.parse("contentpane");
					handleSendMessageSubmit();
					standby.hide();
				} else if(contenturl.indexOf("sendMessage.htm") != -1){
					destroyWidgets();
					updateContentPane(newContent);
					parser.parse("contentpane");
					standby.hide();
				} else {
					console.log("default callback");
					updateContentPane(newContent);
					parser.parse("contentpane");
					
					standby.hide();
				}
				
			}

			
			handleForgotPasswordLoad = function(){
				query("#forgotPasswordLink").on("click", function(e) {
					contenturl = "/public/forgotPassword.htm";
					loadContentPanewithUrl(contenturl);
				});
			}
			
			handleForgotPasswordSubmit = function(){
				var forgotForm = dojo.byId("forgotPasswordForm"); 
				dojo.connect(forgotForm,"onsubmit", function(e) {
					contenturl = "/public/forgotPasswordSubmit.htm";
					
					if(registry.byId("forgotPasswordForm").validate()){ 
						loadContentPanewithUrlPost(contenturl, dojo.byId("forgotPasswordForm"));
					} else {
						
						standby.hide();
					}
				});
			}
			
			handleSendMessageSubmit = function(){
				var forgotForm = dojo.byId("sendMessageForm"); 
				dojo.connect(forgotForm,"onsubmit", function(e) {
					contenturl = "/profile/sendMessage.htm";
					if(registry.byId("sendMessageForm").validate()){ 
						loadContentPanewithUrlPost(contenturl, dojo.byId("sendMessageForm"));
					} else {
						
						standby.hide();
					}
				});
			}
			

			handleReasonRegistrationFormSubmit = function(){
				var reasonForm = dojo.byId("regReasonForm"); 
				dojo.connect(reasonForm,"onsubmit", function(e) {
					var regReasonFormWidget = dijit.byId("regReasonForm");
					if(regReasonFormWidget.validate() && regReasonFormWidget.value.activityTypes.length > 0){						
						contenturl = "/profile/regReasonFormSubmit.htm";
						loadContentPanewithUrlPost("/profile/regReasonFormSubmit.htm", reasonForm);
					} else {
						domStyle.set(dojo.byId("reasonForRegistrationError"), "display", "inline");
					}
					
				});
			}
			
			query("#stopAnim").on("click", function(e){
				continueSlideShowAnimation = null;
				slideShowAnimation.stop();
			});
			
			handleProfileSearch = function(){
				var regForm = dojo.byId("profileSearchSubmit"); 
				dojo.connect(regForm,"onsubmit", function(e) {
					destroyProfileWidgets();
					var searchTerm = dijit.byId("profile_search").get("value");  
					contenturl = "/profile/searchUserProfile.htm";
					loadContentPanewithUrlMaintainWidgetPost(contenturl, dojo.byId("profileSearchSubmit")); 
				});
				
				query("#advanced_search_button").on("click", function(e) {
					var status = domAttr.get(query("#adv_pane_open")[0], "op");
					if(status == 0 ){
						dojox.fx.wipeTo({
						    node: "advanced_search",
						    duration: 300,
						    height: 140
						  }).play();
						domAttr.set(query("#adv_pane_open")[0], "op", "1");
					} else {
						dojox.fx.wipeTo({
						    node: "advanced_search",
						    duration: 300,
						    height: 0
						  }).play();
						domAttr.set(query("#adv_pane_open")[0], "op", "0");
					}
					
				});
			}
			
			handleExtProfileview = function(url){
				contenturl = url;
				loadContentPanewithUrl(contenturl);
			}
			
			
			handleQuestionnaireFormSubmit = function() {
				var qform = dojo.byId("questionnaireForm");
				console.log("questionnaire form handle submit"); 
				dojo.connect(qform, "onsubmit", function(e) {
					console.log("q form submitted"); 
					
					standby.show();
					var xhrArgs = {
						form : dojo.byId("questionnaireForm"),
						url: '/profile/questionnaireSubmit.htm',
						load : function(data) {
							if(data.indexOf("success") != -1){
								//clickmenu(dom.byId("nav_item_1"));
								window.location = "/";
							} else {
								console.log("error : " + data);
							}
							
						},
						error : function(error) {
							console.log("error : " + error);
							dojo.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					}
										
					if(registry.byId("questionnaireForm").validate()){ 
						console.log("q form validated"); 
						xhr.post(xhrArgs);	
						var imageUpoadform = dojo.byId("imageUploadForm");
						if(dojo.byId("image_input").value.length > 0){
							iframe.send({
								method: "post",
							    form: imageUpoadform,
							    headers: {"Content-Type": "multipart/form-data" },
							    handleAs: "json"
							 }).then(function(data){
							    console.log(data);
							 }, function(err){
							    // Handle Error
							 });
						}
					} else {
						console.log("q form validation failed");
						
						standby.hide();
					}
							
				});
			}
			
			handleAddQRow = function(){
				query("#addQuestion").on("click", function(e) {
						console.log("handle add row"); 
					cloneTarget = dojo.byId("temp_clone");
					currentCount = domAttr.get(cloneTarget, "qCount");
					var newQRow = lang.clone(query("#temp_clone").query("tr")[0]);
					var newQAddOptButtonRow = lang.clone(query("#temp_clone").query("tr")[1]);
					domAttr.set(newQRow, "id", "qcount" + currentCount);
					construct.place(newQRow, dojo.byId("qButtonRow"), "before");
					construct.place(newQAddOptButtonRow, dojo.byId("qButtonRow"), "before");
					console.log(query("#qcount" + currentCount).query("input")[0]);
					domAttr.set(query("#qcount" + currentCount).query("textarea")[0], "name", "questions[" + currentCount + "].questionDesc");
					domAttr.set(query("#qcount" + currentCount).query("textarea")[0], "data-dojo-type", "dijit.form.Textarea");
					
					domAttr.set(query("#qcount" + currentCount).query("select")[0], "name", "questions[" + currentCount + "].questionTypeName");
					domAttr.set(query("#qcount" + currentCount).query("select")[0], "data-dojo-type", "dijit.form.Select");
					
					domAttr.set(query("#qcount" + currentCount).query("input")[0], "name", "questions[" + currentCount + "].nonLinkedInUser");
					
					domAttr.set(query("#qcount" + currentCount).query("input")[1], "name", "questions[" + currentCount + "].id");
					console.log(newQAddOptButtonRow);
					domAttr.set(query(newQAddOptButtonRow).query("button")[0], "currentQIndex", currentCount); 
					parser.parse("qcount" + currentCount);
					currentCount++;
					domAttr.set(cloneTarget, "qCount", currentCount);
					handleAddQOption();
				});
			}
			
			handleQuestTypeChange = function(e){
				console.log(e);
				if(e.value == 'MULTI_SELECT' || e.value == 'SELECT_ONE'){
					domStyle.set(query(dojo.byId(e.id)).parent().parent().next()[0], "display", "");
				}else {
					domStyle.set(query(dojo.byId(e.id)).parent().parent().next()[0], "display", "none");
				}
			}
			
			handleAddQOption = function(){
				query(".addOption").on("click", function(e) {
						console.log("handle add option"); 
					
					cloneOptTarget = dojo.byId("temp_clone_option");
					currentButtonTarget = e.currentTarget;
					currentCount = domAttr.get(query(currentButtonTarget)[0], "currentQIndex");
					lastOpt = query(currentButtonTarget).prev();
					var newOpt = lang.clone(query("#temp_clone_option").query("span")[0]);
					
					currentOptIndex = 0;
					if(lastOpt.length){
						currentOptIndex = domAttr.get(lastOpt[0], "currentIndex");
					}
					domAttr.set(newOpt, "id", "qcount" + currentCount + currentOptIndex);
					construct.place(newOpt, query(currentButtonTarget)[0], "before");
					domAttr.set(query(newOpt).query('input')[0], "name", "questions["+ currentCount +"].selectOptions[" + currentOptIndex + "]");
					domAttr.set(query(newOpt)[0], "currentIndex", parseInt(currentOptIndex) + 1);
					parser.parse("qcount" + currentCount + currentOptIndex);
				});
			}			
			
			
			activateChat = function(target){
				contenturl = domAttr.get(target, "content-url");
				
				standby.show();
				xhr.get({
					url : contenturl,
					load : activateChatCallBack,
					error : function() {
						
						standby.hide();
					}
				});
			}
			
			activateChatCallBack = function(token){
				initialize(token);
				domStyle.set("activateChat", "display", "none");
				
				standby.hide();
				setInterval("heartBeat()", 30000);
				chatActivated = true;
			}
			
			
			startChatWindow = function(target){
				if(chatActivated == false){
					console.log("chat not activated ... ");
					
					return;
				}
				contenturl = domAttr.get(target, "window-data-url");
				console.log(" handling startChatWindow using " + target + " and context url "
						+ contenturl);
				
				standby.show();
				xhr.get({
					url : contenturl,
					handleAs:"json",
					load : startChatWindowCallback,
					error : function() {
						
						standby.hide();
					}
				});
			}
			
			var currentLeft = 0;
			var openChats = []; 
			
			startChatWindowCallback = function(newContent, ioargs){
				lang.mixin(newContent, {
					handlepos: {
				        l: 0,
				        t: 0
				    },
				    currentLeft: currentLeft});
				
				var userMatched = new Boolean(0);
				array.forEach(openChats, function(item, i){
					if(item.indexOf(newContent.toUser) != -1){
						userMatched = true;
						return;
					}
				});
				
				if(userMatched == false){
					createChatWindow(newContent);				
					currentLeft += 260;
					openChats.push(newContent.toUser);
					handleChatWindowSubmit(newContent.formId, newContent.inputTextId, newContent.inputId + "history");
				}				
				
				
				standby.hide();
			}
			
			handleLoginSubmit = function(){
				var loginForm = dojo.byId("loginForm");
				dojo.connect(loginForm,"onsubmit", function(e) {
					
					standby.show();
					var xhrArgs = {
						form : dojo.byId("loginForm"),
						url: '/j_spring_security_check',
						load : function(data) {
							if (data.indexOf("loginPageResponse") != -1) {
								destroyWidgets();
								html.set(dojo.byId("contentpane"), data, {
							        executeScripts: true,
							        scriptHasHooks: false,
							        renderStyles: true
							    });								
								parser.parse("login_content_td"); 
								handleLoginSubmit();
								loadUserRegistrationpage();	
							}else {
								window.location = "/";
							}
						},
						error : function(error) {
							dojo.byId("contentpane").innerHTML = "error occurred";
							destroyWidgets();
							
							standby.hide();
						}
					}
					
					if(registry.byId("loginForm").validate()){ 
						xhr.post(xhrArgs);
					} else {
						
						standby.hide();
					}
				});
			}
			
			

			loadContentPane = function(target) {
				contenturl = domAttr.get(target, "content-url");
				console.log(" handling loadContentPane using " + target + " and context url "
						+ contenturl);
				if (contenturl) {
					destroyWidgets();
					if(slideShowAnimation) {
						console.log("stopping animation"); 
						slideShowAnimation.stop();
						continueSlideShowAnimation = null;
					}
					
					standby.show();
					xhr.get({
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					});
				} else {
					dom.byId("contentpane").innerHTML = "";
				}
			}
			
			loadContentPanewithUrl = function(contenturl) {
				console.log(" handling loadContentPane with context url "
						+ contenturl);
				if (contenturl) {
					destroyWidgets();
					
					standby.show();
					xhr.get({
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					});
				} else {
					dom.byId("contentpane").innerHTML = "";
				}
			}
			
			loadContentPanewithUrlMaintainWidget = function(contenturl) {
				console.log(" handling loadContentPane with context url "
						+ contenturl);
				if (contenturl) {
					//destroyWidgets();
					
					standby.show();
					xhr.get({
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					});
				} else {
					dom.byId("contentpane").innerHTML = "";
				}
			}
			
			loadContentPanewithUrlMaintainWidgetPost = function(contenturl, form) {
				console.log(" handling loadContentPane with context url "
						+ contenturl);
				if (contenturl) {
					//destroyWidgets();
					
					standby.show();
					xhr.post({
						form: form,
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					});
				} else {
					dom.byId("contentpane").innerHTML = "";
				}
			}
			
			loadContentPanewithUrlPost = function(contenturl, form) {
				console.log(" handling post request for loadContentPane with context url "
						+ contenturl);
				if (contenturl) {					
					
					standby.show();
					xhr.post({
						form: form,
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					});
				} else {
					dom.byId("contentpane").innerHTML = "";
				}
			}

			submitEvent = function() {
				query(".disable_user").on("click", function(e) {
					
					standby.show();
					contenturl = domAttr.get(e.target, "endpoint");
					userid = domAttr.get(e.target, "userid");
					value = e.target.checked;
					console.log("value checked : " + value);
					var xhrArgs = {
						url : contenturl,
						content : {
							user_id : userid,
							status : value
						},
						load : function(data) {
							
							standby.hide();
							if (data.indexOf("success")) {
								console.log("successfully changed status of user ");
							}
						},
						error : function(error) {
							
							standby.hide();
						}
					}
					xhr.get(xhrArgs);
				});
			}

			destroyWidgets = function() {
				array.forEach(registry.toArray(), function(widget, i) {
					// console.log(widget.declaredClass);
					if (widget.declaredClass != 'dojox.widget.Standby' && widget.declaredClass != 'dijit._MasterTooltip') { 
						widget.destroy();
					}
				});
				// console.log(registry.length);
			}
			
			destroyProfileWidgets = function() {
				array.forEach(registry.toArray(), function(widget, i) {
					if (widget.declaredClass == 'dojoCustom.profileWidget' || widget.declaredClass == 'dojoCustom.paginationWidget') {
						widget.destroy();
					}
				});
			}
			query(".menu_item").on("click", function(e) {
				var newLinkClass = domAttr.get(e.currentTarget, "nav-class");
				console.log(newLinkClass);
				hash(newLinkClass);
			});
			
			query(".menu_item_level2").on("click", function(e) {
				clickmenu(e.currentTarget);
			});
			
			
			query("#signup_home_button_id").on("click", function(e) {
				loadContentPane(e.currentTarget);
				domClass.remove(e.currentTarget, "menu_selected");
				query("#lastRequest").innerHTML('true');
			}); 
			
			
			
			query('#activateChat').on("click",function(e){
				activateChat(e.currentTarget);
			});

			query("#registry_length").on("click", function(e) {
				require([ "dijit/registry", "dojo/_base/array" ], function(registry, array) {
					array.forEach(registry.toArray(), function(widget, i) {
						console.log(widget.declaredClass);
						//widget.destroy();
					});
					console.log(registry.length);
				});
			});

			handleChatSubmit = function() {
				var xhrArgs = {
					url : "/chat/sendChat.htm",
					form : dojo.byId("chat_text_form"),
					load : function(data) {
						dojo.byId("input_chat").innerHTML += (data + "<br/>");
					},
					error : function(error) {
						dojo.byId("input_chat").innerHTML = "";
					}
				}
				submitChat = function(e) {
					console.log(" - send chat handler - called and submitting chat !!");
					xhr.post(xhrArgs);
					return false;
				}
				keyPressHandler = function(e) {
					if (e.type == 'keypress' && e.charOrCode != keys.ENTER) {
						return false;
					}
					if(dojo.isIE){
						//xhr.post(xhrArgs);
					}
					console.log(" key press handler called !!");
				}
				dojo.connect(dojo.byId("send_chat"), "onclick", submitChat);
				dojo.connect(dojo.byId("chat_text_input"), "onkeypress", keyPressHandler);
			}
			
			handleChatWindowSubmit = function(formId, inputTextId, inputHistoryId) {
				var xhrArgs = {
					url : "/chat/sendChat5.htm",
					form : dojo.byId(formId),
					load : function(data) {
						dojo.byId(formId).text.value = "";
						dojo.byId(inputHistoryId).innerHTML += (data + "<BR/>");
					},
					error : function(error) {
						
					}
				}
				
				keyPressHandler = function(e) {
					if (e.type == 'keypress' && e.charOrCode == keys.ENTER && e.shiftKey ) {
						return false;
					} else if(e.type == 'keypress' && e.charOrCode == keys.ENTER){
						e.preventDefault();
						xhr.post(xhrArgs);
						return false;
					}
					if(dojo.isIE){
						//xhr.post(xhrArgs);
					}
				}

				dojo.connect(dojo.byId(inputTextId), "onkeypress", keyPressHandler);
			}

			handleUserRegistrationSubmit = function() {
				var regForm = dojo.byId("registerForm"); 
				dojo.connect(regForm,"onsubmit", function(e) {
					
					standby.show();
					var xhrArgs = {
						form : dojo.byId("registerForm"),
						url: '/public/registerUser.htm',
						load : function(data) {
							//dojo.byId("registrationPane").innerHTML = data;
							
							standby.hide();
							console.log("xhrget response data: " + data);
							if (data == 'success') {
								showReasonForRegistrationPage();
								//console.log(" reloading page for consistency.. ");

								//window.location.reload();
							} else {
								domStyle.set("regFormMessageDiv", "display", "inline");
								console.log(data);
								dojo.byId("regFormMessage").innerHTML = data;
							}
						},
						error : function(error) {
							dojo.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					}
										
					if(registry.byId("registerForm").validate()){ 
						xhr.post(xhrArgs);		
					} else {
						
						standby.hide();
					}
							
				});
			}
			
			showReasonForRegistrationPage = function(){
				contenturl = "/profile/reasonForRegistration.htm";
				console.log("loading page : " + contenturl);
				loadContentPanewithUrl(contenturl); 
			}
			
			
			handleUpdateQSubmit = function() {
				var qform = dojo.byId("addQSubmitButton");
				console.log("q log : " + qform);
				dojo.connect(qform, "onclick", function(e) {
					console.log("q form submitted"); 
					
					standby.show();
					var xhrArgs = {
						form : dojo.byId("updateQ"),
						url: '/admin/updateQuestionsSubmit.htm',
						load : function(data) {
							if(data.indexOf("success") != -1){
								dojo.byId("responseMessage").innerHTML = "Successfully updated Questions.";
							}
							
							standby.hide();
							
						},
						error : function(error) {
							console.log("error : " + error);
							dojo.byId("contentpane").innerHTML = "";
							
							standby.hide();
						}
					}
										
					if(registry.byId("updateQ").validate()){ 
						console.log("q form validated"); 
						xhr.post(xhrArgs);		
					} else {
						console.log("q form validation failed");
						
						standby.hide();
					}
							
				});
			}
			
			
			slideAnimateTest = function(){
				console.log("slide show"); 
			}
			

			loadUserRegistrationpageCallback = function(newContent, ioargs) {
				html.set(dojo.byId("registrationPane"), newContent, {
			        executeScripts: true,
			        scriptHasHooks: false,
			        renderStyles: true
			    });
				parser.parse("registrationPane"); 
				
				standby.hide();
				handleUserRegistrationSubmit();
			}

			loadUserRegistrationpage = function() {
				xhr.get({
					url : '/public/showRegistrationForm.htm',
					load : loadUserRegistrationpageCallback,
					error : function(ioargs) {
						dom.byId("contentpane").innerHTML = "error occured";
					}
				});
			}
			
			googlePopup = function() {
				var popupURL = "/public/login.htm?source=google";
				window.open(popupURL,
								"Popup",
								"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=630,height=450");
			}	
			
			linkedinPopup = function() {
				var popupURL = "/public/login.htm?source=linkedin";
				window.open(popupURL,
								"Popup",
								"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=630,height=450");
			}	
			
		    
		    heartBeat = function(){
		    	var xhrArgs = {
						url: '/chat/heartBeat.htm',
						handleAs: 'json',
						load : function(data) {
							console.log("xhrget response data: " + data);
							updateChatUserList(data);
						},
						error : function(error) {
							console.log("error occurred");
						}
					}
		    	xhr.get(xhrArgs);		
		    }
		    
		    updateChatUserList = function(data){
		    	console.log("updating chat user list.. size: " + data.onlineUsers.length);
		    }
		    
		    if(sessionToken){
		    	activateChatCallBack(sessionToken);
		    }
		    
		    var firstNode = 0;
		    var secondNode = 1;
		    animateSwapImages  = function(imageNodes, textNodes){
		    	fx.combine([
    	    	      baseFx.fadeOut({
    	    	        node: imageNodes[firstNode], 
    	    	        duration: 3000
    	    	      }),
    	    	      baseFx.fadeIn({
      	    	        node: imageNodes[secondNode],
      	    	        duration: 3000,
      	    	        onEnd: function(){
      	    	        	//explode_1(textNodes[0]); 
      	    	        	if(imageNodes.length - 1 == secondNode){
      	    	        		firstNode++;
	      	  		    		secondNode = 0;
	      	  		    	} else if(imageNodes.length - 1 == firstNode){
	      	  		    		firstNode = 0;
	      	  		    		secondNode++;
	      	  		    	} else {
	      	  		    		firstNode++;
	      	  		    		secondNode++;
	      	  		    	}
      	    	        	setTimeout(function(){animateSwapImages(imageNodes, textNodes)},9000); 
      	    	        }
      	    	      })
	    	      ]).play();	    	
		    }
		    
		    
		    
		    
		    dojox.fx._split = function(/*Object*/ args){
		        // summary: Split a node into rectangular pieces and animate them.
		        //
		        // description:
		        //      Returns an animation that will split the node into a grid
		        //      of pieces that move independently.
		        //
		        //  args:
		        //      args.crop: Boolean - If true, pieces will only be visible inside node's boundries
		        //      args.rows: Integer - The number of horizontal pieces (default is 3)
		        //      args.columns: Integer - The number of vertical pieces (default is 3)
		        //      args.pieceAnimation: Function(piece, x, y, coords) - Returns either the dojo._Animation
		        //      or an array of dojo._Animation objects for the piece at location (x, y) in the node's grid;
		        //      coords is the result of dojo.coords(args.node, true);

		        args.node = dojo.byId(args.node);
		        var node = args.node;
		        var s = node.style;
		        var coords = dojo.coords(node, true);

		        args.rows = args.rows || 3;
		        args.columns = args.columns || 3;
		        args.duration = args.duration || 1000;

		        var pieceHeight = coords.h / args.rows;
		        var pieceWidth = coords.w / args.columns;
		        
		        var container = document.createElement("DIV");
		        dojo.style(container, {
		            position: "absolute",
		            top: parseFloat(coords.t) + "px",
		            left: parseFloat(coords.l) + "px",
		            border: "none",
		            height: parseFloat(coords.h) + "px",
		            width: parseFloat(coords.w) + "px",
		            overflow: args.crop ? "hidden" : "visible"
		        });
		        node.parentNode.appendChild(container);

		        var animations = [];

		        // Create the pieces and their animations
		        for(var y = 0; y < args.rows; y++){
		            for(var x = 0; x < args.columns; x++){
		                // Create the piece
		                var piece = document.createElement("DIV");
		                var pieceContents = node.cloneNode(true);
		                var duration = args.duration;

		                dojo.style(piece, {
		                    position: "absolute",
		                    top: (pieceHeight * y) + "px",
		                    left: (pieceWidth * x) + "px",
		                    padding: '0',
		                    margin: '0',
		                    border: "none",
		                    overflow: "hidden",
		                    height: pieceHeight + "px",
		                    width: pieceWidth + "px"
		                });
		                piece.onmouseover = undefined;
		                piece.onmouseout = undefined;
		                piece.onclick = undefined;
		                piece.ondblclick = undefined;
		                piece.oncontextmenu = undefined;

		                dojo.style(pieceContents, {
		                    opacity: "",
		                    position: "relative",
		                    top: 0 - (y * pieceHeight) + "px",
		                    left: 0 - (x * pieceWidth) + "px"
		                });
		                piece.appendChild(pieceContents);
		                container.appendChild(piece);

		                var pieceAnimation = args.pieceAnimation(piece, x, y, coords);
		                if(dojo.isArray(pieceAnimation)){
		                    // if pieceAnimation is an array, append its elements
		                    animations = animations.concat(pieceAnimation);
		                }else{
		                    // otherwise, append it
		                    animations[animations.length] = pieceAnimation;
		                }
		            }
		        }

		        var anim = dojo.fx.combine(animations);
		        dojo.connect(anim, "onEnd", anim, function(){
		            node.parentNode.removeChild(container);
		        });
		        if(args.onPlay){
		            dojo.connect(anim, "onPlay", anim, args.onPlay);
		        }
		        if(args.onEnd){
		            dojo.connect(anim, "onEnd", anim, args.onEnd);
		        }
		        return anim; // dojo._Animation
		    };
		    
		    

		    dojox.fx.blockFadeOut = function(/*Object*/ args){
		        // summary: Split a node into rectangular pieces and fade them
		        //
		        // description:
		        //      Returns an animation that will split the node into a grid
		        //      of pieces that fade in or out.
		        //
		        //  args:
		        //      args.rows: Integer - The number of horizontal pieces (default is 5)
		        //      args.columns: Integer - The number of vertical pieces (default is 5)
		        //      args.interval: Float - The number of milliseconds between each piece's animation (default is 0)
		        //      args.random: Float - If true, pieces have a random delay. The value defines how much
		        //                             randomness is introduced
		        //      args.reverseOrder: Boolean - If true, pieces animate in reversed order
		        //      args.unhide: Boolean - If true, the animation is reversed

		        args.node = dojo.byId(args.node);
		        var node = args.node;
		        var s = node.style;

		        args.rows = args.rows || 5;
		        args.columns = args.columns || 5;
		        args.duration = args.duration || 1000;
		        args.interval = args.interval || args.duration / (args.rows + args.columns * 2);
		        args.random = args.random || 0;
		        var random = Math.abs(args.random);
		        var duration = args.duration - (args.rows + args.columns) * args.interval;

		        // Returns the animation object for each piece
		        args.pieceAnimation = function(piece, x, y, coords){
		            var randomDelay = Math.random() * args.duration;
		            var uniformDelay = (args.reverseOrder) ?
		                (((args.rows + args.columns) - (x + y)) * Math.abs(args.interval)) :
		                ((x + y) * args.interval);
		            var delay = randomDelay * random + Math.max(1 - random, 0) * uniformDelay;
		            // Create the animation object for the piece
		            var pieceAnimation = dojo.animateProperty({
		                node: piece,
		                duration: duration,
		                delay: delay,
		               // easing: (args.easing || easing.sinInOut),
		                properties: {
		                    opacity: (args.unhide ? {start: 0, end: 1} : {end:0})
		                },
		                beforeBegin: (args.unhide ? function(){piece.style.opacity = 0;} : undefined)
		            });

		            return pieceAnimation;
		        };

		        var anim = dojox.fx._split(args);
		        if(args.unhide){
		            dojo.connect(anim, "onEnd", anim, function(){
		                s.opacity = "";
		            });
		        }else{
		            dojo.connect(anim, "onPlay", anim, function(){
		                s.opacity = "0";
		            });
		        }
		        return anim; // dojo._Animation
		    };
		    
		   

		    dojox.fx.blockFadeIn = function(/*Object*/ args){
		        args.unhide = true;
		        return dojox.fx.blockFadeOut(args);
		    };
		    
		    blockfade_2 = function(imageNodes, textNodes){
		    	continueSlideShowAnimation = true;
                var properties = {
                    node: imageNodes[firstNode],
                    random: 0.25,
                    duration: 3000,
                    reverseOrder: true
                };
                
                var properties2 = {
                    node: imageNodes[secondNode],
                    random: 0.25,
                    duration: 3000,
                    reverseOrder: true
                };
               
                properties2.onEnd = function(){   
                	sample_text_disintegrate_2(textNodes[secondNode]).play();
                	if(imageNodes.length - 1 == secondNode){
	    	        		firstNode++;
  	  		    		secondNode = 0;
  	  		    	} else if(imageNodes.length - 1 == firstNode){
  	  		    		firstNode = 0;
  	  		    		secondNode++;
  	  		    	} else {
  	  		    		firstNode++;
  	  		    		secondNode++;
  	  		    	}   
                	
                	setTimeout(function(){
                			if(continueSlideShowAnimation){
                				blockfade_2(imageNodes, textNodes);
                			}
                		},5000); 
                };
                currentAnimation = dojox.fx.blockFadeOut(properties);
                currentAnimation2 = dojox.fx.blockFadeIn(properties2);
                slideShowAnimation = fx.combine([currentAnimation, currentAnimation2, sample_text_disintegrate_1(textNodes[firstNode])]).play();
            }
		    
		    sample_text_disintegrate_2 = function(node){
		    	return dojox.fx.text.type({
	                node: node,
	                duration: 2000,
	                reverseOrder: true,
	                wordDelay: 0,
	                onPlay: function(){domStyle.set(node, "opacity", "");}
	            });
            };
            
            sample_text_disintegrate_1 = function(node){
		    	return dojox.fx.text.blockFadeOut({
	                node: node,
	                duration: 3000,
	                words: true,
	                reverseOrder: true,
	                onPlay: function(){domStyle.set(node, "opacity", "");},
	                onEnd: function(){domStyle.set(node, "opacity", "0");}
	            });
            };
            
            hookDashboardNav = function(){
				query(".dashboard-nav-a").on("click", function(e){ 
					var contentId = domAttr.get(e.currentTarget, "content-id");
					var currentContentId = domAttr.get(query("#dashboard-nav .selected")[0], "content-id") ;
					domClass.remove(query("#dashboard-nav .selected")[0], "selected"); 
					domClass.add(query(e.currentTarget)[0], "selected");
					domStyle.set(dom.byId(currentContentId), "display", "none");
					domStyle.set(dom.byId(contentId), "display", "");
				});
			}
		    
			hash("main_nav_1");
		});
